import { Configuration, App, Inject, IMidwayLogger } from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import * as axios from '@midwayjs/axios';
import * as validate from '@midwayjs/validate';
import * as info from '@midwayjs/info';
import { config } from 'dotenv';

// Load .env file
config();
import { DefaultErrorFilter } from './filter/default.filter';
import { NotFoundFilter } from './filter/notfound.filter';
import { ReportMiddleware } from './middleware/report.middleware';
import { PrismaService } from './service/prisma.service';
import DefaultConfig from './config/config.default';
import UnittestConfig from './config/config.unittest';
import * as swagger from '@midwayjs/swagger';

@Configuration({
  imports: [
    koa,
    axios,
    validate,
    {
      component: info,
      enabledEnvironment: ['local'],
    },
    swagger,
  ],
  importConfigs: [
    {
      default: DefaultConfig,
      unittest: UnittestConfig,
    },
  ],
})
export class MainConfiguration {
  @App('koa')
  app: koa.Application;

  @Inject()
  prismaService: PrismaService;

  @Inject()
  logger: IMidwayLogger;

  async onReady() {
    // BigInt serialization patch
    (BigInt.prototype as any).toJSON = function () {
      return this.toString();
    };

    // Connect to the database
    console.log('Connecting 数据库连接中...');
    try {
      await this.prismaService.$connect();
      console.log('数据库连接成功。');
    } catch (error) {
      console.error('数据库连接失败:', error);
    }

    // add middleware
    this.app.useMiddleware([ReportMiddleware]);
    // add filter
    this.app.useFilter([NotFoundFilter, DefaultErrorFilter]);

    const port = (this.app as any)?.getConfig?.('koa.port') ?? process.env.PORT ?? 7001;
    const host = 'http://127.0.0.1:' + port;
    console.log(`[Swagger] UI: ${host}/swagger-ui/index.html`);
    console.log(`[Swagger] JSON: ${host}/swagger-ui.json`);
  }
}
